//
//  TextAlertView.m
//  自定义AlertView
//
//  Created by 丶离人梦 on 2017/2/9.
//  Copyright © 2017年 丶离人梦. All rights reserved.
//

#import "TextAlertView.h"

@interface TextAlertView ()

@property(nonatomic,assign)BOOL notifiKeyboardHide;

@property(nonatomic,strong)UIView *backgroundView;
@property(nonatomic,strong)UIView *ShowAlertView;
@property(nonatomic,strong)UITextField *MessageTextField;
@property(nonatomic,strong)UIButton *CancelButton;
@property(nonatomic,strong)UIButton *OkButton;

@property(nonatomic,strong)NSString *TitleString;
@property(nonatomic,strong)NSString *CancelString;
@property(nonatomic,strong)NSString *OkString;

@end

@implementation TextAlertView

- (instancetype)initWithTitle:title delegate:delegate cancelButtonTitle:cancelTitle otherButtonTitle:otherTitle {
    if (self = [super initWithFrame:[[UIApplication sharedApplication] keyWindow].frame]) {
        self.TitleString = title;
        self.delegate = delegate;
        self.CancelString = cancelTitle;
        self.OkString = otherTitle;
        
        [self CreateSubView];
    }
    return self;
}

- (void)CreateSubView {
    self.notifiKeyboardHide = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    self.backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    self.backgroundView.backgroundColor = [UIColor blackColor];
    self.backgroundView.alpha = 0.6;
    [self addSubview:self.backgroundView];
    
    self.ShowAlertView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SYRealValue(630 / 2), SYRealValue(380 / 2))];
    self.ShowAlertView.layer.cornerRadius = 5;
    self.ShowAlertView.backgroundColor = [UIColor whiteColor];
    self.ShowAlertView.center = CGPointMake(ScreenWidth / 2, ScreenHeight / 2);
    [self addSubview:self.ShowAlertView];
    
    //标题
    UILabel *TitleLabel = [[UILabel alloc]init];
    TitleLabel.text = self.TitleString;
    TitleLabel.textAlignment = NSTextAlignmentCenter;
    TitleLabel.font = [UIFont systemFontOfSize:SYRealValue(40 / 2)];
    [self.ShowAlertView addSubview:TitleLabel];
    [TitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.ShowAlertView).with.offset(SYRealValue(40 / 2));
        make.left.equalTo(self.ShowAlertView).with.offset(0);
        make.right.equalTo(self.ShowAlertView.mas_right).with.offset(0);
        make.height.mas_equalTo(SYRealValue(50 / 2));
    }];
    
    //输入框
    self.MessageTextField = [[UITextField alloc]init];
    self.MessageTextField.layer.cornerRadius = 5;
    self.MessageTextField.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1];
    self.MessageTextField.keyboardType = UIKeyboardTypeDecimalPad;
    self.MessageTextField.returnKeyType = UIReturnKeyDone;
    [self.ShowAlertView addSubview:self.MessageTextField];
    [self.MessageTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(TitleLabel.mas_bottom).with.offset(SYRealValue(40/ 2));
        make.left.equalTo(self.ShowAlertView).with.offset(SYRealValue(40 / 2));
        make.right.equalTo(self.ShowAlertView.mas_right).with.offset(SYRealValue(-40 / 2));
        make.height.mas_equalTo(SYRealValue(90 / 2));
    }];
    
    [self shakeToShow:self.ShowAlertView];
    
    //取消按钮的背景色
    UIImage *CancelButtonImage = [PublicClass imageWithColor:[UIColor colorWithRed:0.98 green:0.45 blue:0.33 alpha:1]];
    
    self.CancelButton = [[UIButton alloc]initWithFrame:CGRectMake(SYRealValue(40 / 2), SYRealValue(240 / 2), SYRealValue(250 / 2), SYRealValue(100 / 2))];
    [self.CancelButton setBackgroundImage:CancelButtonImage forState:UIControlStateNormal];
    [self.CancelButton setTitle:self.CancelString forState:UIControlStateNormal];
    self.CancelButton.titleLabel.font = [UIFont systemFontOfSize:SYRealValue(40 / 2)];
    [self.CancelButton addTarget:self action:@selector(ButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.CancelButton.tag = 0;
    [self.ShowAlertView addSubview:self.CancelButton];

    //给Button设置圆角
    UIBezierPath *CancelButtonMaskPath = [UIBezierPath bezierPathWithRoundedRect:self.CancelButton.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *CancelButtonMaskLayer = [[CAShapeLayer alloc] init];
    CancelButtonMaskLayer.frame = self.CancelButton.bounds;
    CancelButtonMaskLayer.path = CancelButtonMaskPath.CGPath;
    self.CancelButton.layer.mask = CancelButtonMaskLayer;
    
    //确定按钮的背景色
    UIImage *OkButtonImage = [PublicClass imageWithColor:[UIColor colorWithRed:0.98 green:0.45 blue:0.33 alpha:1]];
    
    self.OkButton = [[UIButton alloc]initWithFrame:CGRectMake(SYRealValue(340 / 2), SYRealValue(240 / 2), SYRealValue(250 / 2), SYRealValue(100 / 2))];
    [self.OkButton setBackgroundImage:OkButtonImage forState:UIControlStateNormal];
    [self.OkButton setTitle:self.OkString forState:UIControlStateNormal];
    self.OkButton.titleLabel.font = [UIFont systemFontOfSize:SYRealValue(40 / 2)];
    [self.OkButton addTarget:self action:@selector(ButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.OkButton.tag = 1;
    [self.ShowAlertView addSubview:self.OkButton];
    
    //给Button设置圆角
    UIBezierPath *OkButtonMaskPath = [UIBezierPath bezierPathWithRoundedRect:self.OkButton.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *OkButtonMaskLayer = [[CAShapeLayer alloc] init];
    OkButtonMaskLayer.frame = self.OkButton.bounds;
    OkButtonMaskLayer.path = OkButtonMaskPath.CGPath;
    self.OkButton.layer.mask = OkButtonMaskLayer;
}

//显示试图
- (void)Show {
    UIView *KeyWindow = [[UIApplication sharedApplication] keyWindow];
    [KeyWindow addSubview:self];
}

//移除试图
- (void)removeAlertView {
    if ([self.MessageTextField isFirstResponder]) {
        [self.MessageTextField resignFirstResponder];
    }
    [UIView animateWithDuration:0.35 animations:^{
        self.backgroundView.alpha = 0;
        [self removeFromSuperview];
        self.backgroundView = nil;
        self.ShowAlertView = nil;
    } completion:^(BOOL finished) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        if (self.notifiKeyboardHide) {
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
        }
    }];
}

- (void)ButtonAction:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(TextAlertView:clickedButtonAtIndex:textMessage:)]) {
        [self.delegate TextAlertView:self clickedButtonAtIndex:(sender.tag) textMessage:self.MessageTextField.text];
    }
    [self removeAlertView];
}

///键盘弹起，页面动画，监听
- (void)keyboardWillShow:(NSNotification *)notification {
    // 键盘的frame
    CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = keyboardRect.size.height;
    
    CGFloat keyboardOriginY = ScreenHeight - keyboardHeight;
    CGFloat operateMaxY = ScreenHeight / 2 + self.ShowAlertView.bounds.size.height / 2 + 16;
    
    if (operateMaxY >= keyboardOriginY) {
        [UIView animateWithDuration:0.25 animations:^{
            CGRect rect = self.ShowAlertView.frame;
            rect.origin.y = keyboardOriginY - rect.size.height - 16;
            self.ShowAlertView.frame = rect;
        } completion:^(BOOL finished) {
            
        }];
        self.notifiKeyboardHide = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }else{
        self.notifiKeyboardHide = NO;
    }
}

///键盘收起，页面动画，监听
- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView animateWithDuration:0.25 animations:^{
        CGRect rect = self.ShowAlertView.frame;
        rect.origin.y = (ScreenHeight - rect.size.height) / 2;
        self.ShowAlertView.frame = rect;
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - 输入框代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    
    return YES;
}

#pragma mark - 弹性震颤动画
- (void)shakeToShow:(UIView *)aView {
    CAKeyframeAnimation *animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.5;
    animation.removedOnCompletion = YES;
    animation.fillMode = kCAFillModeForwards;
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
